package com.anquing.socket03;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author Administrator
 * 服务器线程处理类
 *
 */
public class ServerThread extends Thread {
	//与本线程相关的Socket
	Socket socket = null;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}
	//线程执行操作，响应客户端请求
	@Override
	public void run() {
		//1、获取输入流，并读取客户端信息
		InputStream is=null;
		InputStreamReader isr=null;
		BufferedReader br=null;
		OutputStream os=null;
		PrintWriter pw = null;
		try {
			is = socket.getInputStream();
			isr = new InputStreamReader(is);//将字节输入流转换成字符流
			br = new BufferedReader(isr);//为输入流添加缓冲
			String info = null;
			while((info = br.readLine())!=null){//循环读取客户端的信息
				System.out.println("我是服务器，客户端说："+info);
			}
			//2、关闭输入流
			socket.shutdownInput();
			//3、获取输出流，响应客户端的请求
			os = socket.getOutputStream();
			pw = new PrintWriter(os);//包装为打印流
			pw.write("欢迎您！");
			pw.flush();//调用flush()方法将缓冲输出
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//4、关闭相关的资源
			try {
				if(pw!=null){
					pw.close();
				}
				if(os!=null){
					os.close();
				}
				if(br!=null){
					br.close();
				}
				if(isr!=null){
					isr.close();
				}
				if(is!=null){
					is.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
